<?php

namespace App\Controller\Api;

use App\Base\BaseController4Restful;
use App\Entity\Product;
use App\Entity\ProductStatistic;
use App\Repository\ProductRepository;
use App\Repository\UserRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class ApiProductController extends BaseController4Restful
{
    /**
     * @Route("/api/products", name="apiGetProducts",methods={"GET","POST"})
     */
    public function apiGetProducts(ProductRepository $repository, Request $request,UserRepository $userRepository)
    {
        switch ($request->getMethod()) {
            case "POST":
//                if (!$user = $this->getUser()) {
//                    return $this->json_out(203, "请登录后操作");
//                }
                $data = $this->getRequestData();

//                $data["cat1"] = "/api_/categories/" . $data["cat1"];
//                $data["cat2"] = "/api_/categories/" . $data["cat2"];
                if (!is_array($data["pics"])) {
                    $data["pics"] = json_decode($data["pics"], true);
                }
                $data["cover"] = $data["pics"][0] ?? "";
                /**@var $Product Product */
                $Product = $this->createEntity($data, Product::class);
                $user = $userRepository->findOneBy(array());

                $Product->setUser($user)->setShop($user->getShop())
                    ->setStatus(0)
                    ->setCreateAt(new \DateTime())
                    ->setUpdateAt(new \DateTime());
                $this->myEm()->persist($Product);
                //创建统计数据
                $ProductStatistic = new ProductStatistic();
                $ProductStatistic->setProduct($Product)
                    ->setView(0)
                    ->setHeart(0)
                    ->setScore(0);
                $this->myEm()->persist($ProductStatistic);

                $this->myEm()->flush();
                return $this->json_out(200, "创建成功", $Product);
            default:
                if (!$page = $this->getParamRequired("page")) {
                    $page = 1;
                }
//                $user = $this->getUser();
                $limit = 10;
                $offset = (int)abs($limit * ($page - 1));
                $total = $repository->count([]);
                $this->setMeta($page, $total, $limit);
                $list = $repository->findBy(array(), array("id" => "DESC"), $limit, $offset);
                $this->setGroups("simple");
                return $this->json_out(200, "获取成功", $list);
        }
    }

    /**
     * @Route("/api/products/{id}", name="apiAddProducts",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiUpdateProducts(Product $Product, Request $request)
    {
        $data = $this->getRequestData();
        switch ($request->getMethod()) {
            case "DELETE":
                $this->myEm()->remove($Product);
                $this->myEm()->flush();
                return $this->json_out(200, "已移除");
            case "PATCH":
            case "PUT":
                if (isset($data["cat1"])) {
                    $data["cat1"] = "/api_/categories/" . $data["cat1"];
                    $data["cat2"] = "/api_/categories/" . $data["cat2"];
                    if (isset($data["pics"])&&!is_array($data["pics"])) {
                        $data["pics"] = json_decode($data["pics"], true);
                        $data["cover"] = $data["pics"][0] ?? "";
                    }
                }
                /**@var $Product Product */
                $Product = $this->updateEntity($data, Product::class, $Product);
                $Product->setUpdateAt(new \DateTime());
                $this->myEm()->persist($Product);
                $this->myEm()->flush();
                break;
            case "Get":
            default:
        }

        if (!$ProductStatistic = $Product->getStatistic()){
            $ProductStatistic = new ProductStatistic();
            $ProductStatistic->setScore(0)
                ->setHeart(0)
                ->setProduct($Product)
                ->setView(0);
        }else{
            $ProductStatistic->setView($ProductStatistic->getView() + 1);
        }
        $this->myEm()->persist($ProductStatistic);
        $this->myEm()->flush();

//        $this->setGroups("product", "home", "tags", "tag");
        $this->setGroups("simple");
        $Product = $this->serialize($Product);
        $Product["intro"] = $this->dealWithImgInHtml($Product["intro"]);


        return $this->json_out(200, "获取成功", $Product);
    }


    /**
     * @Route("/api/products/delete/{id}", name="apiAddProductsDelete",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiAddProductsDelete(Product $Product, Request $request)
    {
        $user = $this->needToBeUser();
        if ($user != $Product->getUser() || $Product->getStatus() > 199) {
            return $this->json_out(400,"数据异常");
        }

        $this->myEm()->remove($Product);$this->myEm()->flush();
        return $this->json_out(200,"删除成功");
    }


}
